//
//  TradingRecordViewController.m
//  ZYZB
//
//  Created by ENERGY on 2018/7/9.
//  Copyright © 2018年 ENERGY. All rights reserved.
//

#import "TradingRecordViewController.h"
#import "HoldingTradeRecordTableViewCell.h"
#import "HavePayedTradeRecordTableViewCell.h"
#import "UnPayedTradeRecordTableViewCell.h"
#import "WithdrawTradeRecordTableViewCell.h"
#import "BidInformationViewController.h"
#import "LendContractViewController.h"
#import "InterestDetailViewController.h"
@interface TradingRecordViewController ()<UITableViewDelegate, UITableViewDataSource>
@property (nonatomic, strong)UITableView * tableView;
@property (nonatomic, strong)UIView * headerView;
@property (nonatomic, strong)UIView * topBarView;//构造Bar
@property (nonatomic, strong)UIButton * holdingBtn;//持有中
@property (nonatomic, strong)UIButton * havePayedBtn;//已付款
@property (nonatomic, strong)UIButton * unPayedBtn;//未付款
@property (nonatomic, strong)UIButton * withdrawBtn;//已撤销
@property (nonatomic, strong)UIView * moveLineView;//移动横线
@property (nonatomic, strong)NSString * titleStr;//标题id(0:持有中1:已还款2:未支付3:已撤销)
@property (nonatomic, strong)NSMutableArray * cellData;
@property (nonatomic, assign)int currentPage;//当前页码
@property (nonatomic, strong)UILabel * titleLab;//表头多少笔记录说明
@end

@implementation TradingRecordViewController(networking)
//标的系列
- (void)getTrdingRecordData{
    NSString * timeStr = [self currentTimeStr];
    //str
    NSDictionary * dic = @{
                           @"userName":[UserModel sharedInstanced].mobile,
                           @"token":[UserModel sharedInstanced].token,
                           @"phone":[UserModel sharedInstanced].mobile,
                           @"numm":self.titleStr,
                           @"page":@(1),
                           @"t":timeStr
                           };
    //sign
    NSDictionary * signDic = @{
                               @"userName":[UserModel sharedInstanced].mobile,
                               @"token":[UserModel sharedInstanced].token,
                               @"phone":[UserModel sharedInstanced].mobile,
                               @"numm":self.titleStr,
                               @"page":@(1),
                               @"t":timeStr,
                               @"merchantNo":@"80d709a97af1b8ab"
                               };
    SortMD5Code * md5Code = [[SortMD5Code alloc] init];
    NSString * jsonStr = [md5Code getJsonWithStrDic:dic withSignDic:signDic];
    NSData *postData = [jsonStr dataUsingEncoding:NSUTF8StringEncoding];
    NSURL *url = [NSURL URLWithString:@"http://120.78.157.132:82/index.php/order/index?api=api1004"];
    NSMutableURLRequest *request = [NSMutableURLRequest requestWithURL:url];
    //设置请求方式
    request.HTTPMethod = @"POST";
    //设置请求参数
    request.HTTPBody = postData;
    [NSURLConnection sendAsynchronousRequest:request queue:[NSOperationQueue mainQueue] completionHandler:^(NSURLResponse * _Nullable response, NSData * _Nullable data, NSError * _Nullable connectionError) {
        [self hiddenProgressHUD];
        if (connectionError) {
            if (connectionError.code == -1001) {
                [self.view makeToast:@"请求网络超时，请稍后再试" duration:1 position:CSToastPositionCenter];
            }
        }else{
            NSDictionary *dictionary =[NSJSONSerialization JSONObjectWithData:data options:NSJSONReadingMutableLeaves error:nil];//data解析为dictionary
            if (!dictionary) {
                NSLog(@"数据缺失");
                return;
            }
            NSString * compareMD5Str = [md5Code encodeStringWithDictionary:dictionary];
            NSString * signResult = [dictionary objectForKey:@"sign"];//接到的json串sign字段
            NSDictionary * jsonData = [md5Code getNSDictionaryData:dictionary];//解析为字典数据
            if ([jsonData[@"code"] isEqualToString:@"000000"]) {
                if ([jsonData[@"body"] count] > 0) {
                    if ([compareMD5Str isEqualToString:signResult]) {
                        if (self.currentPage == 1) {
                            [self.cellData removeAllObjects];
                        }
                        [self.cellData addObjectsFromArray:jsonData[@"body"]];
                        if ([self.titleStr isEqualToString:@"0"]) {
                            self.titleLab.text = [NSString stringWithFormat:@"持有中出借项目共%lu笔", (unsigned long)self.cellData.count];
                        }
                        if ([self.titleStr isEqualToString:@"1"]) {
                            self.titleLab.text = [NSString stringWithFormat:@"已还款出借项目共%lu笔", (unsigned long)self.cellData.count];
                        }
                        if ([self.titleStr isEqualToString:@"2"]) {
                            self.titleLab.text = [NSString stringWithFormat:@"未支付出借项目共%lu笔", (unsigned long)self.cellData.count];
                        }
                        if ([self.titleStr isEqualToString:@"3"]) {
                            self.titleLab.text = [NSString stringWithFormat:@"已撤销出借项目共%lu笔", (unsigned long)self.cellData.count];
                        }
                        [self.tableView reloadData];
                        NSLog(@"成功");
                    }
                }else{
                    if (self.currentPage == 1) {
                        [self.cellData removeAllObjects];
                    }
                    [self.cellData addObjectsFromArray:jsonData[@"body"]];
                    if ([self.titleStr isEqualToString:@"0"]) {
                        self.titleLab.text = @"持有中出借项目共0笔";
                    }
                    if ([self.titleStr isEqualToString:@"1"]) {
                        self.titleLab.text = @"已还款出借项目共0笔";
                    }
                    if ([self.titleStr isEqualToString:@"2"]) {
                        self.titleLab.text = @"未支付出借项目共0笔";
                    }
                    if ([self.titleStr isEqualToString:@"3"]) {
                        self.titleLab.text = @"已撤销出借项目共0笔";
                    }
                    [self.cellData removeAllObjects];
                    ShowMessage(jsonData[@"msg"]);
                }
            }else{
                ShowMessage(jsonData[@"msg"]);
            }
        }
    }];
}
@end
@implementation TradingRecordViewController
- (void)viewDidLoad {
    [super viewDidLoad];
    self.navigationItem.title = @"交易记录";
    //返回按钮
    UIButton * backBtn = [[UIButton alloc] initWithFrame:CGRectMake(18/WIDTH_6_SCALE, 14/WIDTH_6_SCALE + 24 + 20, 24/WIDTH_6_SCALE, 30/WIDTH_6_SCALE)];
    [backBtn addTarget:self action:@selector(backBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    [backBtn setImage:[UIImage imageNamed:@"out"] forState:UIControlStateNormal];
    UIBarButtonItem * leftItem = [[UIBarButtonItem alloc] initWithCustomView:backBtn];
    self.navigationItem.leftBarButtonItem = leftItem;
    self.view.backgroundColor = [UIColor whiteColor];
    
    [self topBarViewSetUp];//初始化控件
    if (@available(iOS 11.0, *)) {
        self.tableView.contentInsetAdjustmentBehavior = UIScrollViewContentInsetAdjustmentNever;
    }else {
        self.automaticallyAdjustsScrollViewInsets = NO;
    }
    [self.view addSubview:self.tableView];
    self.titleStr = @"0";
    [self getTrdingRecordData];//网络接口
}
//构造Bar
- (void)topBarViewSetUp{
    self.topBarView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 44/WIDTH_6_SCALE)];
    [self.view addSubview:self.topBarView];
    //按钮
    int tradeBtnW = SCREEN_WIDTH/4;
    int tradeBtnH = _topBarView.height - 2/WIDTH_6_SCALE;
    for (int i = 0; i<4; i++) {
        UIButton * btn = [[UIButton alloc] initWithFrame:CGRectMake(tradeBtnW*i, 0, tradeBtnW, tradeBtnH)];
        btn.tag = 4000+i;
        [_topBarView addSubview:btn];
    }
    //持有中按钮
    self.holdingBtn = (UIButton *)[self.view viewWithTag:4000];
    self.holdingBtn.titleLabel.font = DEF_FontSize_12;
    [self.holdingBtn setTitle:@"持有中" forState:UIControlStateNormal];
    [self.holdingBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [self.holdingBtn setTitleColor:getColor(@"767676") forState:UIControlStateNormal];
    [self.holdingBtn addTarget:self action:@selector(holdingBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    self.holdingBtn.selected = YES;
    //已还款按钮
    self.havePayedBtn = (UIButton*)[self.view viewWithTag:4001];
    self.havePayedBtn.titleLabel.font = DEF_FontSize_12;
    [self.havePayedBtn setTitle:@"已还款" forState:UIControlStateNormal];
    [self.havePayedBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [self.havePayedBtn setTitleColor:getColor(@"767676") forState:UIControlStateNormal];
    [self.havePayedBtn addTarget:self action:@selector(havePayedBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //未支付按钮
    self.unPayedBtn = (UIButton*)[self.view viewWithTag:4002];
    self.unPayedBtn.titleLabel.font = DEF_FontSize_12;
    [self.unPayedBtn setTitle:@"未支付" forState:UIControlStateNormal];
    [self.unPayedBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [self.unPayedBtn setTitleColor:getColor(@"767676") forState:UIControlStateNormal];
    [self.unPayedBtn addTarget:self action:@selector(unPayedBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //已撤销按钮
    self.withdrawBtn = (UIButton*)[self.view viewWithTag:4003];
    self.withdrawBtn.titleLabel.font = DEF_FontSize_12;
    [self.withdrawBtn setTitle:@"已撤销" forState:UIControlStateNormal];
    [self.withdrawBtn setTitleColor:[UIColor orangeColor] forState:UIControlStateSelected];
    [self.withdrawBtn setTitleColor:getColor(@"767676") forState:UIControlStateNormal];
    [self.withdrawBtn addTarget:self action:@selector(withdrawBtnClick:) forControlEvents:UIControlEventTouchUpInside];
    //移动横线
    self.moveLineView = [[UIView alloc] initWithFrame:CGRectMake(0, self.holdingBtn.bottom, 44/WIDTH_6_SCALE, 2/WIDTH_6_SCALE)];
    self.moveLineView.centerX = self.holdingBtn.centerX;
    self.moveLineView.backgroundColor = [UIColor orangeColor];
    [_topBarView addSubview:self.moveLineView];
}
- (UIView *)headerView{
    if (!_headerView) {
        _headerView = [[UIView alloc] initWithFrame:CGRectMake(0, 0, SCREEN_WIDTH, 49/WIDTH_6_SCALE)];
        _headerView.backgroundColor = [UIColor whiteColor];
        int borderW = 18/WIDTH_6_SCALE;
        UILabel * titleLab = [[UILabel alloc] initWithFrame:CGRectMake(borderW, 0, SCREEN_WIDTH - 2*borderW, _headerView.height - 1/WIDTH_6_SCALE)];
//        titleLab.text = @"持有中出借项目共2笔";
        titleLab.font = DEF_FontSize_12;
        [_headerView addSubview:titleLab];
        self.titleLab = titleLab;
        UIView * lineView = [[UIView alloc] initWithFrame:CGRectMake(borderW, _headerView.bottom - 1/WIDTH_6_SCALE, SCREEN_WIDTH - 2*borderW, 1/WIDTH_6_SCALE)];
        lineView.backgroundColor = getColor(grayColor);
        [_headerView addSubview:lineView];
    }return _headerView;
}
- (UITableView *)tableView{
    if (!_tableView) {
        _tableView = [[UITableView alloc] initWithFrame:CGRectMake(0, self.topBarView.bottom, SCREEN_WIDTH, SCREEN_HEIGHT - NAVI_HEIGHT - BOTTOM_HEIGHT - self.topBarView.height) style:UITableViewStylePlain];
        _tableView.tableHeaderView = self.headerView;
        [_tableView registerClass:[HoldingTradeRecordTableViewCell class] forCellReuseIdentifier:NSStringFromClass([HoldingTradeRecordTableViewCell class])];
        [_tableView registerClass:[HavePayedTradeRecordTableViewCell class] forCellReuseIdentifier:NSStringFromClass([HavePayedTradeRecordTableViewCell class])];
        [_tableView registerClass:[UnPayedTradeRecordTableViewCell class] forCellReuseIdentifier:NSStringFromClass([UnPayedTradeRecordTableViewCell class])];
        [_tableView registerClass:[WithdrawTradeRecordTableViewCell class] forCellReuseIdentifier:NSStringFromClass([WithdrawTradeRecordTableViewCell class])];
        _tableView.separatorStyle = UITableViewCellSeparatorStyleNone;
        _tableView.dataSource = self;
        _tableView.delegate = self;
    }return _tableView;
}
- (NSMutableArray *)cellData{
    if (!_cellData) {
        _cellData = @[].mutableCopy;
    }return _cellData;
}
#pragma mark - tableViewDelegate和tableViewDataSource
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath{
    UITableViewCell * cell = nil;
    if ([self.titleStr isEqualToString:@"0"]) {
        HoldingTradeRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HoldingTradeRecordTableViewCell class]) forIndexPath:indexPath];
        cell.model = self.cellData[indexPath.row];
        cell.contractBtnBlock = ^(){
            LendContractViewController * lendContractVC = [[LendContractViewController alloc] init];
            [self.navigationController pushViewController:lendContractVC animated:YES];
        };
        cell.interestBtnBlock = ^{
            InterestDetailViewController * interestDetailVC = [[InterestDetailViewController alloc] init];
            [self.navigationController pushViewController:interestDetailVC animated:YES];
        };
        return cell;
    }
    if ([self.titleStr isEqualToString:@"1"]) {
        HavePayedTradeRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([HavePayedTradeRecordTableViewCell class]) forIndexPath:indexPath];
        cell.model = self.cellData[indexPath.row];
        return cell;
    }
    if ([self.titleStr isEqualToString:@"2"]) {
        UnPayedTradeRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([UnPayedTradeRecordTableViewCell class]) forIndexPath:indexPath];
        cell.model = self.cellData[indexPath.row];
        return cell;
    }
    if ([self.titleStr isEqualToString:@"3"]) {
        WithdrawTradeRecordTableViewCell * cell = [tableView dequeueReusableCellWithIdentifier:NSStringFromClass([WithdrawTradeRecordTableViewCell class]) forIndexPath:indexPath];
        cell.model = self.cellData[indexPath.row];
        return cell;
    }
    return cell;
}
- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath{
    BidInformationViewController * vc = [[BidInformationViewController alloc] init];
    vc.bidID = [self.cellData[indexPath.row] objectForKey:@"bid"];
    [self.navigationController pushViewController:vc animated:YES];
}
- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath{
    return 111/WIDTH_6_SCALE;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section{
    return self.cellData.count;
}
- (NSInteger)numberOfSectionsInTableView:(UITableView *)tableView{
    return 1;
}
#pragma mark - action
- (void)backBtnClick:(UIButton *)sender{
    [self.navigationController popViewControllerAnimated:YES];
}
- (void)holdingBtnClick:(UIButton *)sender{
    self.holdingBtn.selected = YES;
    self.havePayedBtn.selected = NO;
    self.unPayedBtn.selected = NO;
    self.withdrawBtn.selected = NO;
    self.titleStr = @"0";
    [self getTrdingRecordData];//网络接口
    [UIView animateWithDuration:0.5 animations:^{
        self.moveLineView.centerX = sender.centerX;
    }];
}
- (void)havePayedBtnClick:(UIButton *)sender{
    self.holdingBtn.selected = NO;
    self.havePayedBtn.selected = YES;
    self.unPayedBtn.selected = NO;
    self.withdrawBtn.selected = NO;
    self.titleStr = @"1";
    [self getTrdingRecordData];//网络接口
    [UIView animateWithDuration:0.5 animations:^{
        self.moveLineView.centerX = sender.centerX;
    }];
}
- (void)unPayedBtnClick:(UIButton *)sender{
    self.holdingBtn.selected = NO;
    self.havePayedBtn.selected = NO;
    self.unPayedBtn.selected = YES;
    self.withdrawBtn.selected = NO;
    self.titleStr = @"2";
    [self getTrdingRecordData];//网络接口
    [UIView animateWithDuration:0.5 animations:^{
        self.moveLineView.centerX = sender.centerX;
    }];
}
- (void)withdrawBtnClick:(UIButton *)sender{
    self.holdingBtn.selected = NO;
    self.havePayedBtn.selected = NO;
    self.unPayedBtn.selected = NO;
    self.withdrawBtn.selected = YES;
    self.titleStr = @"3";
    [self getTrdingRecordData];//网络接口
    [UIView animateWithDuration:0.5 animations:^{
        self.moveLineView.centerX = sender.centerX;
    }];
}
@end
